<!-- 用户管理 -->
<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
  <div class="user-page art-full-height">
    <!-- 搜索栏 -->
    <UserSearch v-show="showSearchBar" v-model="searchForm" :departments="departments" :roles="roles" :salers="salers"
      @search="handleSearch" @reset="resetSearchParams">
    </UserSearch>

    <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" v-model:showSearchBar="showSearchBar" :loading="loading"
        @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton v-auth="'add'" type="primary" @click="showDialog('add')" v-ripple>新增用户</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable :loading="loading" :data="data" :columns="columns" :pagination="pagination"
        @selection-change="handleSelectionChange" @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange">
      </ArtTable>

      <!-- 用户弹窗 -->
      <UserDialog v-model:visible="dialogVisible" :type="dialogType" :user-data="currentUserData"
        :departments="departments" :roles="roles" :salers="salers" @submit="handleDialogSubmit" />

      <!-- 修改密码弹窗 -->
      <PasswordDialog v-model:visible="pwdDialogVisible" :user-id="pwdDialogUserId" :username="pwdDialogUsername"
        @submit="refreshData" />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import { fetchGetUserList } from '@/api/system-manage'
import UserSearch from './modules/user-search.vue'
import UserDialog from './modules/user-dialog.vue'
import PasswordDialog from './modules/password-dialog.vue'
import { useSystemStore } from '@/store/modules/system'
import { deleteUser as deleteUserApi } from '@/api/system/user'

defineOptions({ name: 'User' })

type UserListItem = Api.SystemManage.UserListItem

const showSearchBar = ref(false)

// 接入 system store 数据
const system = useSystemStore()
const departments = computed(() => system.getDepartments)
const roles = computed(() => system.getRoles)
const salers = computed(() => system.getSalers)

onMounted(async () => {
  await system.init(['departments', 'salers', 'roles'])
})

// 弹窗相关
const dialogType = ref<Form.DialogType>('add')
const dialogVisible = ref(false)
const currentUserData = ref<Partial<UserListItem>>({})

// 选中行
const selectedRows = ref<UserListItem[]>([])

// 搜索表单
const searchForm = ref({
  username: undefined,
  userGender: undefined,
  userPhone: undefined,
  userEmail: undefined,
  status: '1'
})


const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  resetSearchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable({
  // 核心配置
  core: {
    apiFn: fetchGetUserList,
    apiParams: {
      current: 1,
      size: 20,
      ...searchForm.value
    },
    // 排除 apiParams 中的属性
    excludeParams: [],
    columnsFactory: () => [
      {
        prop: 'id',
        label: 'ID',
        sortable: true,
        width: 80,
        checked: false,
        formatter: (row) => row.id
      },
      {
        prop: 'username',
        label: '用户',
        sortable: true,
        formatter: (row) => row.username,
        width: 80
      },
      {
        prop: 'name', label: '姓名', sortable: true, formatter: (row) => row.name, width: 100
      },
      { prop: 'email', label: '邮箱', formatter: (row) => row.email },
      { prop: 'department', label: '部门', formatter: (row) => row.department, checked: false },
      { prop: 'dept_name', label: '名称', formatter: (row) => row.dept_name },
      { prop: 'person_id', label: '人员ID', formatter: (row) => row.person_id, width: 80, checked: false },

      {
        prop: 'roles',
        label: '角色',
        formatter: (row) => {
          const roleIds: number[] = Array.isArray(row.roles)
            ? (row.roles as number[]) : []
          if (!roleIds.length) {
            return h(ElTag, { type: 'info', effect: 'plain', size: 'small' }, () => '无')
          }

          // 使用系统 store 的 roles 列表构建 id->name 映射
          const idToName = new Map((roles.value || []).map((r: any) => [Number(r.id), String(r.name)]))

          return h(
            'div',
            { style: 'display:flex;flex-wrap:wrap;gap:6px;align-items:center;' },
            roleIds.map((rid) =>
              h(ElTag, { type: 'success', effect: 'plain', size: 'small' }, () => idToName.get(Number(rid)) || String(rid))
            )
          )
        }
      },
      {
        prop: 'create_time',
        label: '创建日期',
        sortable: true,
        formatter: (row) => row.create_time
      },
      {
        prop: 'operation',
        label: '操作',
        width: 165,
        aglin: 'right', // 固定列
        formatter: (row) =>
          h('div', [
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => showDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => deleteUser(row)
            }),
            h(ArtButtonTable, {
              type: 'more',
              onClick: () => showPwdDialog(row)
            })
          ])
      }
    ]
  }
})

/**
 * 搜索处理
 * @param params 参数
 */
const handleSearch = (params: Record<string, any>) => {
  console.log(params)
  // 搜索参数赋值
  Object.assign(searchParams, params)
  getData()
}

/**
 * 显示用户弹窗
 */
const showDialog = (type: Form.DialogType, row?: UserListItem): void => {
  dialogType.value = type
  currentUserData.value = row || {}
  nextTick(() => {
    dialogVisible.value = true
  })
}

/**
 * 删除用户
 */
const deleteUser = async (row: UserListItem): Promise<void> => {
  console.log('删除用户:', row)
  try {
    await ElMessageBox.confirm(`确定要注销该用户吗？`, '注销用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })

    if (!row?.id) {
      ElMessage.error('缺少用户ID，无法删除')
      return
    }

    await deleteUserApi(Number(row.id))
    ElMessage.success('注销成功')
    // 删除成功后刷新列表
    refreshData()
  } catch (error) {
    // 用户取消或接口失败
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

/**
 * 处理弹窗提交事件
 */
const handleDialogSubmit = async () => {
  // 仅在子组件确认提交成功时刷新列表
  dialogVisible.value = false
  currentUserData.value = {}
  refreshData()
}

/**
 * 处理表格行选择变化
 */
const handleSelectionChange = (selection: UserListItem[]): void => {
  selectedRows.value = selection
  console.log('选中行数据:', selectedRows.value)
}

// 修改密码弹窗状态与逻辑
const pwdDialogVisible = ref(false)
const pwdDialogUserId = ref<number | undefined>(undefined)
const pwdDialogUsername = ref<string>('')

const showPwdDialog = (row: UserListItem): void => {
  pwdDialogUserId.value = Number(row.id)
  pwdDialogUsername.value = String(row.username || '')
  pwdDialogVisible.value = true
}
</script>

<style lang="scss" scoped></style>
